$(document).ready(function(){
	var complete_task = function(el) {
		id = $(el).attr('data-task')
		console.log("COMPLETE TASK => " + id);
		$.ajax({
			type: 'GET',
			url: '/tasks',
			data: {
				action: 'complete',
				id: id,
				completed: true
			}
		}).done(function(msg) {
			$(el).hide();
			console.log(msg);
		});
	};

	var destroy_task = function(el) {
		id = $(el).attr('data-task')
		console.log("DELETE TASK => " + id);
		$.ajax({
			type: 'GET',
			url: '/tasks',
			data: {
				action: 'delete',
				id: id
			}
		}).done(function(msg) {
			$(el).hide();
			console.log(msg);
		});
	}

	var task_item = function(task) {
		return '<li data-task="' + task.id + '"><button rel="done" class="btn btn-success btn-mini"><i class="icon-ok"></i></button> '+task.content+'</li>';
	};

	var render_task_items = function(tasks) {
		$('#tasks').empty();
		for(var i = 0; i<tasks.length; i++) {
			$('#tasks').append(task_item(tasks[i]));
		}
		$('li button[rel="done"]').click(function(){
			complete_task($(this).parent('li'));
		});
		$('li button[rel="delete"]').click(function(){
			destroy_task($(this).parent('li'));
		});
	};


	var fetch_tasks = function() {
		$.get('/tasks').done(function(msg) {
			window.tasks = JSON.parse(msg);
			render_task_items(window.tasks);
		});
	};

	$('#create_task').click(function() {
		content = $('#new_task').val();
		if(content.length < 1) {
			return false;
		}
		$.ajax({
			type: 'POST',
			url: '/tasks',
			data: {
				content: content
			}
		}).done(function(msg){
			$('#new_task').val('');
		});
		fetch_tasks();
		return false;
	});


	fetch_tasks();
});